package com.mars.diancan.service.impl;

import com.mars.diancan.common.ResultEnum;
import com.mars.diancan.dto.OrderDTO;
import com.mars.diancan.exception.DiancanException;
import com.mars.diancan.service.BuyerService;
import com.mars.diancan.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author MARS
 * @date 2018/6/27
 */
@Service
@Slf4j
public class BuyerServiceImpl implements BuyerService {

    @Autowired
    private OrderService orderService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderId) {
        return checkOrderOwner(openid,orderId);
    }

    /**
     * 取消订单
     * @param openid
     * @param orderId
     * @return
     */
    @Override
    public OrderDTO cancelOrder(String openid, String orderId) {
        OrderDTO orderDTO = checkOrderOwner(openid,orderId);
        // 取消订单要判断  orderDto不能为空
        if (orderDTO == null){
            log.error("取消订单，查不到该订单，orderId={}",orderId);
            throw new DiancanException(ResultEnum.ORDER_NOT_EXIST);
        }
        return orderService.cancel(orderDTO);
    }

    private OrderDTO checkOrderOwner(String openid, String orderId) {
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (orderDTO == null) {
            return null;
        }
        // 进行openid的校验，判断是否是自己的
        if (!orderDTO.getBuyerOpenid().equalsIgnoreCase(openid)) {
            log.error("查询订单，订单的openid不一致，openid={}",openid);
            throw new DiancanException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderDTO;
    }
}
